package com.qf.fmall.shopcard.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall.index.entity.Product;
import com.qf.fmall.index.entity.ProductImg;
import com.qf.fmall.index.mapper.ProductDao;
import com.qf.fmall.index.mapper.ProductImgDao;
import com.qf.fmall.product.entity.ProductSku;
import com.qf.fmall.product.mapper.ProductSkuDao;
import com.qf.fmall.shopcard.entity.ShoppingCart;
import com.qf.fmall.shopcard.mapper.ShoppingCartDao;
import com.qf.fmall.shopcard.service.IShoppingCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author leon
 * @since 2024-01-19
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartDao, ShoppingCart> implements IShoppingCartService {


    @Autowired
    private ProductDao productDao;
    @Autowired
    private ProductImgDao productImgDao;

    @Autowired
    private ProductSkuDao productSkuDao;
    @Override
    public List<ShoppingCart> listCart(Integer userId) {

        //根据userid查询购物车
        List<ShoppingCart> data = list(new QueryWrapper<ShoppingCart>().eq("user_id", userId));


        addExtraInfo(data);


        return data;
    }

    private void addExtraInfo(List<ShoppingCart> data) {
        //
//                "productName": "咪咪小虾条",
//                "productImg": "mmxt_1.png",
//                "skuName": "咪咪虾条 单包 50g",
//                "originalPrice": 2,
//                "sellPrice": 1,
//                "stock": 254
//


        //查询前端需要的额外信息
        for (ShoppingCart cart : data) {
                //处理商品名字
            Integer productId = cart.getProductId();
            Product product = productDao.selectById(productId);
            cart.setProductName(product.getProductName());


            //处理商品图片啊
            ProductImg productImg = productImgDao.selectOne(new QueryWrapper<ProductImg>().eq("product_id", productId).eq("is_main", 1));

            cart.setProductImg(productImg.getUrl());



            //处理商品呢套餐信息

            String skuId = cart.getSkuId();
            ProductSku productSku = productSkuDao.selectById(skuId);
            cart.setSkuName(productSku.getSkuName());
            cart.setOriginalPrice(productSku.getOriginalPrice());
            cart.setSellPrice(productSku.getSellPrice());
            cart.setStock(productSku.getStock());

        }
    }

    @Override
    public List<ShoppingCart> listbycids(List<String> cids) {

        //根据购物车主键 查询购物车信息
        List<ShoppingCart> data = list(new QueryWrapper<ShoppingCart>().in("cart_id", cids));

        addExtraInfo(data);

        return data;
    }
}
